#!/bin/bash
yum -y install wget
cd ~
rm -rf nginx*.tar.*
nver=1.18.0
wget http://nginx.org/download/nginx-$nver.tar.gz
tar zxvf nginx-$nver.tar.gz

#install dependencies
yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel
# modules
yum -y install libxslt-devel gd-devel perl-devel perl-ExtUtils-Embed
a=$(find . -name "openssl*.tar.gz")
if [ -f $a ];then
    tar -zxvf $a
else
    sslv=1.1.1g
    wget --no-check-certificate https://www.openssl.org/source/openssl-$sslv.tar.gz
    tar -zxvf openssl-$sslv.tar.gz
fi
cd openssl*
opendir=$(pwd)
cd ..

cd nginx*
# ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_realip_module --with-http_ssl_module --with-openssl=$opendir --with-http_gzip_static_module --with-pcre --with-http_dav_module --with-http_v2_module
#create user
useradd -s /sbin/nologin -M nginx
./configure --prefix=/usr/share/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/run/nginx.pid --user=nginx --group=nginx --with-http_ssl_module --with-openssl=$opendir --with-ipv6 --with-http_v2_module --with-http_realip_module --with-stream_ssl_preread_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-http_auth_request_module --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

make && make install

#optimization
rm -rf /usr/sbin/nginx
ln -s /usr/share/nginx/sbin/nginx /usr/sbin/
cat >/usr/lib/systemd/system/nginx.service<<-EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl enable nginx
systemctl start nginx